/**
 * 登录问题诊断工具
 * 用于排查和诊断登录相关的问题
 */

import { getUserInfo, isTokenValid } from './tokenManager';

/**
 * 诊断登录状态
 * @returns {Object} 诊断结果
 */
export function diagnoseLoginStatus() {
    const userInfo = getUserInfo();
    const tokenValid = isTokenValid();
    
    const diagnosis = {
        timestamp: new Date().toISOString(),
        userInfo,
        tokenValid,
        localStorage: {
            available: typeof localStorage !== 'undefined',
            token: localStorage.getItem('token'),
            userId: localStorage.getItem('userId'),
            email: localStorage.getItem('userEmail'),
            avatar: localStorage.getItem('touxiang')
        },
        network: {
            online: navigator.onLine,
            userAgent: navigator.userAgent
        },
        issues: []
    };
    
    // 检查问题
    if (!userInfo.isLoggedIn) {
        diagnosis.issues.push('用户未登录');
    }
    
    if (!tokenValid) {
        diagnosis.issues.push('Token无效或已过期');
    }
    
    if (!localStorage.getItem('token')) {
        diagnosis.issues.push('本地存储中没有token');
    }
    
    if (!navigator.onLine) {
        diagnosis.issues.push('网络连接离线');
    }
    
    return diagnosis;
}

/**
 * 测试API连接
 * @param {string} baseURL API基础URL
 * @returns {Promise<Object>} 测试结果
 */
export async function testAPIConnection(baseURL = '/api') {
    const result = {
        success: false,
        baseURL,
        timestamp: new Date().toISOString(),
        error: null,
        response: null
    };
    
    try {
        // 测试简单的GET请求
        const response = await fetch(`${baseURL}/health`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        result.success = response.ok;
        result.response = {
            status: response.status,
            statusText: response.statusText,
            headers: Object.fromEntries(response.headers.entries())
        };
        
        if (response.ok) {
            try {
                const data = await response.json();
                result.response.data = data;
            } catch (e) {
                result.response.data = '无法解析响应数据';
            }
        }
        
    } catch (error) {
        result.error = {
            name: error.name,
            message: error.message,
            stack: error.stack
        };
    }
    
    return result;
}

/**
 * 测试登录API
 * @param {string} email 测试邮箱
 * @param {string} password 测试密码
 * @returns {Promise<Object>} 测试结果
 */
export async function testLoginAPI(email = 'test@example.com', password = 'test123') {
    const result = {
        success: false,
        timestamp: new Date().toISOString(),
        request: { email, password },
        response: null,
        error: null
    };
    
    try {
        const params = new URLSearchParams();
        params.append('email', email);
        params.append('pwd', password);
        
        const response = await fetch('/health/user/v1/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params
        });
        
        result.response = {
            status: response.status,
            statusText: response.statusText,
            headers: Object.fromEntries(response.headers.entries())
        };
        
        if (response.ok) {
            try {
                const data = await response.json();
                result.response.data = data;
                result.success = data.status === '0000';
            } catch (e) {
                result.response.data = '无法解析响应数据';
            }
        }
        
    } catch (error) {
        result.error = {
            name: error.name,
            message: error.message,
            stack: error.stack
        };
    }
    
    return result;
}

/**
 * 清除所有登录相关数据
 */
export function clearAllLoginData() {
    try {
        // 清除localStorage
        localStorage.removeItem('token');
        localStorage.removeItem('userId');
        localStorage.removeItem('userEmail');
        localStorage.removeItem('touxiang');
        
        // 清除sessionStorage
        sessionStorage.removeItem('token');
        sessionStorage.removeItem('userId');
        sessionStorage.removeItem('userEmail');
        sessionStorage.removeItem('touxiang');
        
        // 清除cookies
        document.cookie.split(";").forEach(function(c) { 
            document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
        });
        
        console.log('所有登录数据已清除');
        return true;
    } catch (error) {
        console.error('清除登录数据失败:', error);
        return false;
    }
}

/**
 * 生成诊断报告
 * @returns {string} 诊断报告文本
 */
export function generateDiagnosticReport() {
    const diagnosis = diagnoseLoginStatus();
    
    let report = `=== 登录诊断报告 ===\n`;
    report += `时间: ${diagnosis.timestamp}\n`;
    report += `用户状态: ${diagnosis.userInfo.isLoggedIn ? '已登录' : '未登录'}\n`;
    report += `Token状态: ${diagnosis.tokenValid ? '有效' : '无效'}\n`;
    report += `网络状态: ${diagnosis.network.online ? '在线' : '离线'}\n\n`;
    
    if (diagnosis.issues.length > 0) {
        report += `发现的问题:\n`;
        diagnosis.issues.forEach((issue, index) => {
            report += `${index + 1}. ${issue}\n`;
        });
        report += `\n`;
    }
    
    report += `本地存储状态:\n`;
    report += `- Token: ${diagnosis.localStorage.token ? '存在' : '不存在'}\n`;
    report += `- 用户ID: ${diagnosis.localStorage.userId ? '存在' : '不存在'}\n`;
    report += `- 邮箱: ${diagnosis.localStorage.email ? '存在' : '不存在'}\n`;
    report += `- 头像: ${diagnosis.localStorage.avatar ? '存在' : '不存在'}\n\n`;
    
    report += `浏览器信息:\n`;
    report += `- User Agent: ${diagnosis.network.userAgent}\n`;
    
    return report;
}

/**
 * 在控制台打印诊断信息
 */
export function logDiagnosticInfo() {
    console.group('🔍 登录状态诊断');
    console.log('诊断时间:', new Date().toLocaleString());
    
    const diagnosis = diagnoseLoginStatus();
    console.log('用户信息:', diagnosis.userInfo);
    console.log('Token状态:', diagnosis.tokenValid ? '✅ 有效' : '❌ 无效');
    console.log('网络状态:', diagnosis.network.online ? '✅ 在线' : '❌ 离线');
    
    if (diagnosis.issues.length > 0) {
        console.warn('发现的问题:', diagnosis.issues);
    }
    
    console.log('本地存储:', diagnosis.localStorage);
    console.groupEnd();
}




